package com.my.jwt.shiro.thread.service;


import com.my.jwt.shiro.thread.AppLoginContext;
import com.my.jwt.shiro.thread.domain.SessionUser;
import com.my.jwt.shiro.thread.domain.TFTBLoginParam;
import com.my.jwt.shiro.thread.domain.TftbUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

//@Service
public class TftbUserServiceImpl  implements TftbUserService {


    @Autowired
    private AppLoginContext loginContext;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String login(TFTBLoginParam param) {
        SessionUser sessionUser  =  getSessionUser(param);
        return createToken(sessionUser);
    }

    public String createToken(SessionUser sessionUser) {
        return   loginContext.createToken(sessionUser,AppLoginContext.APP_TFTB_TOKEN_PFE,AppLoginContext.APP_TFTB_TOKEN_SUFF,AppLoginContext.T_USERINFO_KEY);
    }
    public SessionUser getSessionUser(TFTBLoginParam param) {
        SessionUser sessionUser = new SessionUser();
        //按身份证号码查是否存在
//        LambdaQueryWrapper<TftbUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(TftbUser::getIdNumber,param.getIdNumber());
//        lambdaQueryWrapper.last("limit 1");
//        TftbUser user =  baseMapper.selectOne(lambdaQueryWrapper);
        TftbUser user = null;
        if (null == user){
            //create
            String id = add(param);
            sessionUser.setId(id);
        }else {
            update(user,param);
            sessionUser.setId(user.getId());
        }
        //
        sessionUser.setRealname(param.getRealName());
        sessionUser.setUsername(param.getUsername());
        sessionUser.setTelephone(param.getEmployeeMobile());
        sessionUser.setIdCardNum(param.getIdNumber());
//        sessionUser.setUserType(CommonConstant.CUSTOMER);
        sessionUser.setRealStatus(10);
        return sessionUser;
    }

    public String add(TFTBLoginParam param) {
        TftbUser tftbUser = new TftbUser();
        BeanUtils.copyProperties(param,tftbUser);
        tftbUser.setUserName(param.getUsername());
//        baseMapper.insert(tftbUser);
        return tftbUser.getIdNumber();
    }


    public void update(TftbUser user, TFTBLoginParam param) {
        BeanUtils.copyProperties(param,user);
        user.setUserName(param.getUsername());
//        baseMapper.updateById(user);
    }

}
